
(function ({ markdownitContainer: container,
             markdownItAnchor,
             markdownItTocDoneRight,
             markdownitEmoji,
             markdownItTaskCheckbox,
             markdownitMathjax,
             markdownlint,
             markdownlintRuleHelpers
}) {
  function createContainer (klass, defaultTitle) {
    return [
      container, klass, {
        render (tokens, idx) {
          const token = tokens[idx];
          const info = token.info.trim();//.slice(klass.length).trim();
          const types = ['success', 'info', 'warning', 'error'];
          let type = 'info';
          let title = '';
          if (types.indexOf(info) >= 0) {
            type = info;
          }
          switch (type) {
            case 'success':
              title = '成功';
              break;
            case 'warning':
              title = '警告';
              break;
            case 'error':
              title = '错误';
              break;
            default:
              title = '提示';
              break;
          }


          if (token.nesting === 1) {
            let alertCls = `markdown__alert markdown__alert--${type}`;
            let hasTitle = false;
            let titleEl = hasTitle ? `<span class="markdown__alert-message"> ${title}</span>` : ''
            return `
                <div class="${alertCls}">
                  ${titleEl}
                  <span class="markdown__alert-desc">
              `
          } else {
            return `</span></div>`
          }
        }
      }]
  }

  function markdownLint(content) {
    var newLineRe = /\r\n|\r|\n/;
    var allLintErrors = [];

    var errors = function errors() {
      // Numbered
      var lines = content.split(newLineRe);
      var padding = lines.length.toString().replace(/\d/g, " ");
      var options = {
        "strings": {
          "content": content
        },
        "config": {
          "MD013": false,
        },
        "handleRuleFailures": true,
        "resultVersion": 3
      };
      allLintErrors = markdownlint.sync(options).content;
      return allLintErrors;
    };

    return markdownlintRuleHelpers.applyFixes(content, errors())
  }



  function createWrapper(md) {
    const render = md.render;
    const wrapper = md.options.wrapper || 'section';
    const hasWrap = md.options.hasWrap;
    const wrapperClass = md.options.wrapperClass || 'markdown__view';
    const lint = md.options.lint;
    md.render = function(src, env) {
      var  result;
      if (!!lint && markdownlint && markdownlintRuleHelpers) {
        result = render.call(md, markdownLint(src), env);
      } else {
        result = render.call(md, src, env);
      }
      if (!hasWrap) return result;
      return `
      <${wrapper} id="markdownPreviewer" class="${wrapperClass}">
      ${result}
      </${wrapper}>
    `;
    };
  }

  function loadPlugins(md) {

    createWrapper(md);
    md.use(...createContainer('tip', 'TIP'))
      .use(...createContainer('success', 'SUCCESS'))
      .use(...createContainer('info', 'INFO'))
      .use(...createContainer('warning', 'WARNING'))
      .use(...createContainer('error', 'ERROR'));
    markdownItAnchor && md.use(markdownItAnchor, {
        level: 6,
      });


    markdownitEmoji && md.use(markdownitEmoji);
    markdownItTaskCheckbox && md.use(markdownItTaskCheckbox, {
      disabled: false,
      divWrap: false,
      divClass: 'checkbox',
      idPrefix: 'cbx_',
      ulClass: 'markdown__list-task',
      liClass: 'markdown__list-task-item'
    });

    markdownitMathjax && md.use(markdownitMathjax());

    markdownItTocDoneRight && md.use(markdownItTocDoneRight,{
      containerClass: 'markdown__toc-content',
      itemClass: 'md-toc-item',
      linkClass: 'md-toc-inner',
      placeholder: '(\\{:toc\\}|\\[TOC\\]|\\$\\{toc\\}|\\[\\[?_?toc_?\\]?\\]|\\$\\<toc(\\{[^}]*\\})\\>|\\<extoc\\>\\<\\/extoc\\>)'
    });
  }

  window.markdownItPlugins = {
    loadPlugins
  }
})(window);
